const { resolve } = require('path')
const { defineConfig, externalizeDepsPlugin } = require('electron-vite')
const vue = require('@vitejs/plugin-vue')
const fs = require('fs-extra')

// 复制服务器文件的函数
async function copyServerFiles() {
  const srcDir = resolve(__dirname, 'src/main/server')
  const destDir = resolve(__dirname, 'out/main/server')
  await fs.copy(srcDir, destDir, {
    overwrite: true,
    preserveTimestamps: true
  })
  console.log('Server files copied successfully')
}

module.exports = defineConfig({
  main: {
    plugins: [
      externalizeDepsPlugin(),
      {
        name: 'copy-server-files',
        buildStart() {
          return copyServerFiles()
        },
        watchChange(id, change) {
          if (id.includes('src/main/server')) {
            return copyServerFiles()
          }
        }
      }
    ],
    build: {
      outDir: 'out/main',
      emptyOutDir: false,
      rollupOptions: {
        input: {
          index: resolve(__dirname, 'src/main/index.js')
        },
        external: [
          'express',
          'cors',
          'mysql2',
          'nodemailer',
          'dotenv',
          'redis',
          'bcryptjs',
          'jsonwebtoken',
          /^src\/main\/server\/.*/
        ]
      }
    }
  },
  preload: {
    plugins: [externalizeDepsPlugin()],
    build: {
      outDir: 'out/preload'
    }
  },
  renderer: {
    resolve: {
      alias: {
        '@': resolve('src/renderer/src')
      }
    },
    plugins: [vue()],
    root: 'src/renderer',
    publicDir: 'public',
    build: {
      outDir: resolve(__dirname, 'out/renderer'),
      assetsDir: '.',
      emptyOutDir: true,
      rollupOptions: {
        input: {
          index: resolve(__dirname, 'src/renderer/index.html')
        }
      }
    }
  }
})
